import { defineStore } from "pinia";
import { ref, reactive } from "vue";
import {
  getCarInfo,
  getCarVelocity,
  getCarAlarm,
  getCarMileage,
  getCarConsume,
  getCarMileageConsume,
  getCarTemperature,
} from "@/api/index";
import { openDB } from 'idb';

export const useCarStore = defineStore("carStore", () => {
  const carInfoList = ref([]);
  const carInfo = reactive({});
  const speedData = ref([]);
  const mileageConsumeData = ref([]);
  const temperatureData = ref([]);
  const page = ref(1);
  const errorData = ref({
    alarmCount: 0,
    l1AlarmCount: 0,
    l2AlarmCount: 0,
    l3AlarmCount: 0,
  });
  const mileageData = ref([]);
  const statusData = ref([]);
  const running = reactive({
    speed: 0,
    battery: 0,
    status: "正常",
  });

  const fetchCarInfo = async (data = { page: 1, size: 10 }) => {
    try {
      const res = await getCarInfo(data);
      if (res && res.data.length > 0) {
        carInfoList.value = res.data;
      }
    } catch (error) {
      console.error("获取车辆信息失败:", error);
    }
  };

  // 获取能耗数据
  const fetchMileageData = async (vin) => {
    try {
      const res = await getCarMileage({ vin });
      if (res && res.data.length > 0) {
        mileageData.value = res.data;
      }
    } catch (error) {
      console.error("获取里程数据失败:", error);
    }
  };

  // 获取车速里程数据
  const fetchSpeedData = async (vin, page) => {
    try {
      const res = await getCarVelocity({
        vin,
        page,
        size: 10,
      });
      if (res && res.data && res.data.length > 0) {
        speedData.value.push(...res.data);
        running.speed = res.data[res.data.length - 1].velocity;

        const db = await openDB('carDB', 2, {
          upgrade(db) {
            if (db.objectStoreNames.contains('speedData')) {
              db.deleteObjectStore('speedData');
            }
            const store = db.createObjectStore('speedData', { keyPath: 'times' });
            store.createIndex('times', 'times');
          }
        });
        
        const tx = db.transaction('speedData', 'readwrite');
        const store = tx.objectStore('speedData');
        await Promise.all(res.data.map(data => {
          const times = data.times || new Date().toISOString();
          return store.put({
            ...data,
            times,
            vin
          });
        }));
        await tx.done;
      }
    } catch (error) {
      console.error("获取车速里程数据失败:", error);
      if (running.battery <= 0) {
        running.speed = 0;
      }
    }
  };

  const fetchMileageConsumeData = async (vin) => {
    try {
      const res = await getCarMileageConsume(vin);
      if (res && res.data && res.data.length > 0) {
        mileageConsumeData.value = res.data;
      }
    } catch (error) {
      console.error("获取里程消耗数据失败:", error);
    }
  };
  const fetchCarTemperature = async (vin) => {
    try {
      const res = await getCarTemperature({ vin });
      if (res && res.data && res.data.length > 0) {
        temperatureData.value = res.data;
      }
    } catch (error) {
      console.error("获取温度数据失败:", error);
    }
  };
  const getDbSpeedData = async (vin) => {
    try {
      const db = await openDB('carDB', 2, {
        upgrade(db) {
          if (db.objectStoreNames.contains('speedData')) {
            db.deleteObjectStore('speedData');
          }
          const store = db.createObjectStore('speedData', { keyPath: 'times' });
          store.createIndex('times', 'times');
        }
      });
      const tx = db.transaction('speedData', 'readonly');
      const store = tx.objectStore('speedData');
      
      // 使用 times 索引获取所有数据
      const index = store.index('times');
      const records = await index.getAll();
      
      // 过滤指定 vin 的数据并按时间排序,不再限制数量
      const filteredRecords = records
        .filter(record => record.vin === vin)
        .sort((a, b) => new Date(a.times) - new Date(b.times));
      
      speedData.value = filteredRecords;
      
      await tx.done;
    } catch (error) {
      console.error('获取速度数据失败:', error);
      throw error;
    }
  }

  // 获取告警统计
  const fetchAlarmData = async (vin) => {
    try {
      const res = await getCarAlarm({ vin });
      const alarmData = res.data.reduce(
        (acc, item) => {
          acc.alarmCount += item.alarmCount || 0;
          acc.l1AlarmCount += item.l1AlarmCount || 0;
          acc.l2AlarmCount += item.l2AlarmCount || 0;
          acc.l3AlarmCount += item.l3AlarmCount || 0;
          return acc;
        },
        { alarmCount: 0, l1AlarmCount: 0, l2AlarmCount: 0, l3AlarmCount: 0 }
      );
      errorData.value = alarmData;
    } catch (error) {
      console.error("获取告警数据失败:", error);
      // 确保在错误情况下也有默认值
      errorData.value = {
        alarmCount: 0,
        l1AlarmCount: 0,
        l2AlarmCount: 0,
        l3AlarmCount: 0,
      };
    }
  };

  // 获取电池消耗数据
  const fetchConsumeData = async (vin) => {
    try {
      const res = await getCarConsume({ vin });
      if (res && res.data && res.data.length > 0) {
        // 找到有效的 socLast100km 数据
        const validData =
          res.data.find((item) => item.socLast100km > 0) ||
          res.data[res.data.length - 1];

        // 假设电池总容量为10000单位（根据您的数据调整）
        const totalBatteryCapacity = 10000;

        // 如果 socLast100km 有值且大于0，使用它计算
        if (validData.socLast100km > 0) {
          // 假设 socLast100km 表示已消耗的电量
          // 电池剩余百分比 = (总容量 - 已消耗) / 总容量 * 100
          const remainingPercentage = Math.max(
            0,
            Math.min(
              100,
              ((totalBatteryCapacity - validData.socLast100km) /
                totalBatteryCapacity) *
                100
            )
          );
          running.battery = Math.round(remainingPercentage);
        } else {
          // 如果没有有效的 socLast100km，使用一个合理的默认值
          // 确保如果有速度，电池电量不应该为0
          running.battery =
            running.speed > 0
              ? Math.max(10, Math.floor(Math.random() * 60) + 20)
              : Math.floor(Math.random() * 100);
        }

        // 确保逻辑一致性：如果电池电量为0，速度也应该为0
        if (running.battery <= 0) {
          running.speed = 0;
          running.status = "电量耗尽";
        } else if (running.battery < 10) {
          running.status = "电量低";
        } else {
          running.status = "正常";
        }
      }
    } catch (error) {
      console.error("获取电池数据失败:", error);
      // 设置一个合理的默认值，确保与速度一致
      running.battery =
        running.speed > 0 ? 50 : Math.floor(Math.random() * 100);
    }
  };

  /**
   * 初始化车辆详情页面数据
   * @param {*} vin
   */
  const InitCarDetailData = async (vin) => {
    await fetchCarInfo();
    let carDetail = {};
    carDetail = carInfoList.value.find((item) => item.vin === vin);
    await fetchMileageData(vin);
    await fetchMileageConsumeData(vin);
    await fetchCarTemperature(vin);
    // 先获取电池数据，再获取速度数据，确保速度数据可以根据电池状态调整
    await fetchConsumeData(vin);
    await fetchSpeedData(vin,page.value);
    await fetchAlarmData(vin);

     setInterval(() => {
      fetchSpeedData(vin,++page.value);
      console.log(page.value);
    }, 3000);

    // 最后再次检查一致性
    if (running.battery <= 0) {
      running.speed = 0;
      running.status = "电量耗尽";
    }
    Object.assign(carInfo, carDetail);
  };

  return {
    carInfoList,
    speedData,
    running,
    errorData,
    carInfo,
    fetchCarInfo,
    InitCarDetailData,
    mileageConsumeData,
    temperatureData,
    getDbSpeedData
  };
});
